package de.gwtprime.server.servlets;

import java.io.IOException;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import de.gwtprime.server.model.Article;
import de.gwtprime.server.model.ArticleComment;
import de.gwtprime.server.model.ArticleSection;
import de.gwtprime.server.model.Question;
import de.gwtprime.server.sql.HibernateEntityMangerSingelton;
import de.gwtprime.server.sql.helper.HibernateHelper;

public class HibernateTestingServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;


	private static Logger logger = Logger.getLogger(HibernateTestingServlet.class.getName());


	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {

		if(true){
			resp.getWriter().println("!.....!..");
		}


		List<Question> questions = Question.getQuestionsForUser("janpumpe@googlemail.com", 5);
		
		for(Question q : questions){
			resp.getWriter().println(q.getTitle());
		}
		EntityManagerFactory entityManagerFactory = HibernateEntityMangerSingelton.getEntityManagerFactory();
		EntityManager entityManager = entityManagerFactory.createEntityManager();
		entityManager.getTransaction().begin();




		Article article2 = new Article("New article!!!", "Test");
		ArticleSection as = new ArticleSection("zzzzzz", "bbbbb");
		ArticleSection as2 = new ArticleSection("Section2", "Text2");
		
		ArticleComment comment = new ArticleComment();
		comment.setText("sdfsdfsf");
		
		
		article2.addComment(comment);
		
		
		as.setArticle(article2);
		article2.getSections().add(as);

		article2.getSections().add(as2);
		as2.setArticle(article2);
		
		HibernateHelper.persist(article2);
		
		
		entityManager.getTransaction().commit();
		entityManager.close();



		
		

		
		resp.getWriter().println("done");
	}

}
